package thread;

//懒汉式--延迟创建-在使用时创建实例
//线程不安全
class SingletonLazy {

    private static volatile SingletonLazy instance = null;

    private static Object lock = new Object();

    public static SingletonLazy getInstance() {
        //单线程中连续两个相同的if没有意义
        //在多线程中，两次判定之间可能存在其他线程，把if中的instance修改了，导致两次if结果可能不同
        if (instance == null) {//判断是否需要加锁
            synchronized (lock) {
                if (instance == null) {//判断是否需要new对象
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }

    private SingletonLazy() {

    }

}

public class Demo28 {
    public static void main(String[] args) {
        SingletonLazy s1 = SingletonLazy.getInstance();
        SingletonLazy s2 = SingletonLazy.getInstance();
        System.out.println(s1 == s2);

//        SingletonLazy s3 = new SingletonLazy();
    }
}
